import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserById, getUserMenuPermissions } from '@/request/auth-api'
import type { UserInfo } from '@/request/auth-api'
import { useMenuStore } from './menu'
import router from '@/router'

// 定义一个与菜单存储兼容的路由类型
// 这里我们允许component是一个字符串，因为菜单存储会处理这种情况
interface MenuRoute {
  path: string
  component?: string | any
  name?: string
  redirect?: string
  meta?: {
    title?: string
    icon?: string
    hidden?: boolean
    [key: string]: any
  }
  children?: MenuRoute[]
}

// UserInfo interface is now imported from auth-api.ts

/**
 * 认证模块的Store
 */
export const useAuthStore = defineStore('auth', () => {
  // 用户token
  const token = ref<string>(localStorage.getItem('token') || '')
  // 用户信息
  const userInfo = ref<UserInfo | null>(null)
  // 加载状态
  const loading = ref(false)

  // 初始化用户信息
  try {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo);
    }
  } catch (error) {
    console.error('解析用户信息失败:', error);
    localStorage.removeItem('userInfo');
  }

  /**
   * 设置Token
   * @param newToken 新的Token
   */
  function setToken(newToken: string) {
    token.value = newToken;
    // Store token using consistent key name
    localStorage.setItem('access_token', newToken);
    // Keep 'token' for backward compatibility
    localStorage.setItem('token', newToken);
  }

  /**
   * 设置用户信息
   * @param info 用户信息
   */
  function setUserInfo(info: UserInfo) {
    userInfo.value = info;
    localStorage.setItem('userInfo', JSON.stringify(info));
  }

  /**
   * 用户登录
   * @param loginData 登录数据
   */
  async function userLogin(loginData: { username: string; password: string }) {
    loading.value = true
    try {
      // 登录获取用户信息和token
      const res = await login(loginData)
      if (res.code === 0 && res.data) {
        setToken(res.data.access_token)
        setUserInfo(res.data.user)
        
        // 登录成功后获取菜单权限
        try {
          await getMenuPermissions()
        } catch (permError) {
          console.error('登录成功后获取菜单权限失败:', permError)
        }
        
        return res
      } else {
        throw new Error(res.errorMsg || '登录失败')
      }
    } catch (error) {
      console.error('登录出错:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 用户退出登录
   */
  async function userLogout() {
    try {
      // 先调用退出登录接口
      await logout();
    } catch (error) {
      console.error('退出登录出错:', error);
    } finally {
      // 无论接口是否成功，都清除本地状态
      token.value = '';
      userInfo.value = null;
      localStorage.removeItem('token');
      localStorage.removeItem('access_token');
      localStorage.removeItem('userInfo');
      
      // 同时清除菜单路由缓存
      localStorage.removeItem('menu_routes');
      const menuStore = useMenuStore();
      menuStore.resetState();
    }
  }

  /**
   * 检查是否已登录
   */
  function isLoggedIn(): boolean {
    return !!token.value;
  }

  /**
   * 获取用户信息
   * @param userId 用户ID
   */
  async function getUserInfo(userId: number) {
    try {
      const userRes = await getUserById(userId)
      if (userRes.code !== 0 || !userRes.data) {
        throw new Error(userRes.errorMsg || '获取用户信息失败')
      }
      
      // 更新用户信息
      setUserInfo(userRes.data)
      return userRes.data
    } catch (error) {
      console.error('获取用户信息出错:', error)
      throw error
    }
  }

  /**
   * 获取用户菜单权限
   */
  async function getMenuPermissions() {
    try {
      // 获取路由配置
      const menuStore = useMenuStore()
      menuStore.loading = true
      
      // 从 API 获取用户菜单权限
      const res = await getUserMenuPermissions()
      
      if (res.code !== 0 || !res.data) {
        throw new Error(res.errorMsg || '获取菜单权限失败')
      }
      
      console.log('从 API 获取到的用户菜单权限:', res.data)
      
      // 将API返回的权限数据转换为菜单路由格式
      const menuRoutes = convertPermissionsToRoutes(res.data)
      
      // 设置菜单路由
      menuStore.setRoutes(menuRoutes)
      
      return res.data
    } catch (error) {
      console.error('获取菜单权限出错:', error)
      throw error
    } finally {
      const menuStore = useMenuStore()
      menuStore.loading = false
    }
  }

  /**
   * 将API返回的权限数据转换为菜单路由格式
   * @param apiData API返回的数据
   * @returns 菜单路由数组
   */
  function convertPermissionsToRoutes(apiData: any): MenuRoute[] {
    console.log('原始权限数据格式:', apiData)
    
    // 默认菜单路由（始终包含首页）
    const routes: MenuRoute[] = [
      {
        path: '/dashboard',
        component: 'Layout',
        children: [
          {
            path: '',
            name: 'Dashboard',
            component: '@/views/dashboard/Dashboard.vue',
            meta: { title: '首页', icon: 'house' }
          }
        ]
      }
    ]

    // 如果API直接返回了菜单路由数组，直接使用
    if (Array.isArray(apiData) && apiData.length > 0 && apiData[0].path) {
      // 返回其中的首页菜单，加上API返回的其他菜单
      const nonDashboardMenus = apiData.filter(item => item.path !== '/dashboard')
      return [...routes, ...nonDashboardMenus]
    }

    // 如果API返回的是权限数组，需要转换为菜单路由
    if (Array.isArray(apiData)) {
      // 项目管理菜单
      const hasProjectPermission = apiData.some(p => p.name && (p.name.includes('项目') || p.name.includes('project')))
      if (hasProjectPermission) {
        routes.push({
          path: '/project',
          component: 'Layout',
          redirect: '/project/list',
          meta: { title: '项目管理', icon: 'document' },
          children: [
            {
              path: 'list',
              name: 'ProjectList',
              component: '@/views/project/List.vue',
              meta: { title: '项目列表', icon: 'list' }
            }
          ]
        })
      }

      // 服务器管理菜单
      const hasServerPermission = apiData.some(p => p.name && (p.name.includes('服务器') || p.name.includes('运维') || p.name.includes('server')))
      if (hasServerPermission) {
        routes.push({
          path: '/server',
          component: 'Layout',
          redirect: '/server/list',
          meta: { title: '服务器管理', icon: 'cpu' },
          children: [
            {
              path: 'list',
              name: 'ServerList',
              component: '@/views/server/List.vue',
              meta: { title: '服务器列表', icon: 'list' }
            }
          ]
        })
      }

      // 部署管理菜单
      const hasDeployPermission = apiData.some(p => p.name && (p.name.includes('部署') || p.name.includes('发布') || p.name.includes('deploy') || p.name.includes('release')))
      if (hasDeployPermission) {
        routes.push({
          path: '/deploy',
          component: 'Layout',
          redirect: '/deploy/list',
          meta: { title: '部署管理', icon: 'upload' },
          children: [
            {
              path: 'list',
              name: 'DeployList',
              component: '@/views/deploy/List.vue',
              meta: { title: '部署列表', icon: 'list' }
            }
          ]
        })
      }

      // 系统管理菜单
      const hasSystemPermission = apiData.some(p => p.name && (p.name.includes('系统') || p.name.includes('管理员') || p.name.includes('admin') || p.name.includes('system')))
      if (hasSystemPermission) {
        routes.push({
          path: '/system',
          component: 'Layout',
          redirect: '/system/users',
          meta: { title: '系统管理', icon: 'setting' },
          children: [
            {
              path: 'users',
              name: 'UserManagement',
              component: '@/views/user/List.vue',
              meta: { title: '用户管理', icon: 'user' }
            },
            {
              path: 'roles',
              name: 'RoleManagement',
              component: '@/views/role/List.vue',
              meta: { title: '角色管理', icon: 'user' }
            },
            {
              path: 'permissions',
              name: 'PermissionManagement',
              component: '@/views/system/permission/List.vue',
              meta: { title: '权限管理', icon: 'lock' }
            }
          ]
        })
      }
    }

    console.log('转换后的菜单路由:', routes)
    return routes
  }

  return {
    token,
    userInfo,
    loading,
    setToken,
    setUserInfo,
    userLogin,
    userLogout,
    isLoggedIn,
    getUserInfo,
    getMenuPermissions
  }
});
